package edu.ynu.onlinesqltool.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import edu.ynu.onlinesqltool.model.*;

public class SQLExcution {
	private static DaoHelper daoHelper = DaoHelperImpl.getBaseDaoInstance();
	public static int quey(List records,String sql,int pageNo,int size) throws SQLException{
		Connection conn = daoHelper.getConnection();
		PreparedStatement stmt = null;
		ResultSet rs = null;
		ResultSetMetaData rsmd = null; 
		ArrayList list = new ArrayList();
		String sql_ = sql+"";
		//try{
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while(rs.next()){
				Record record = new Record();
				rsmd = rs.getMetaData();
				ArrayList dataItems = new ArrayList();
				for(int i=1;i<=rsmd.getColumnCount();i++){
					DataItem dataItem = new DataItem();
				    dataItem.setColumnName(rsmd.getColumnName(i));
				    dataItem.setColumnValue(rs.getString(i));
			        dataItems.add(dataItem);
			        //record.setDataItems(dataItems);
				}
				list.add(dataItems);
			}
			int total = list.size();
			if(pageNo*size <= total){
				records.addAll(list.subList((pageNo-1)*size, pageNo*size));
			}
			else{
				records.addAll(list.subList((pageNo-1)*size, total));
			}
		//}catch(SQLException e){
			//throw e;
		//}
			daoHelper.closeConnection(conn);
			daoHelper.closePreparedStatement(stmt);
			daoHelper.closeResult(rs);
			return total;
	}
	public static int update(String sql) throws SQLException{
		Connection conn = daoHelper.getConnection();
		PreparedStatement stmt = null;
		stmt = conn.prepareStatement(sql);
		int count = stmt.executeUpdate();
		daoHelper.closeConnection(conn);
		daoHelper.closePreparedStatement(stmt);
		return count;
	}
}
